<template>
  <div class="watermark-container" v-if="userFullName">
    <!-- 可见水印层 - 增加到8个固定位置 -->
    <div class="visible-watermarks">
      <!-- 中心水印 -->
      <div class="watermark watermark-center">
        {{ userFullName }}
      </div>
      
      <!-- 四个角的水印 -->
      <div class="watermark watermark-top-left">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-top-right">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-bottom-left">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-bottom-right">
        {{ userFullName }}
      </div>
      
      <!-- 边缘中点水印 -->
      <div class="watermark watermark-top-center">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-bottom-center">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-left-center">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-right-center">
        {{ userFullName }}
      </div>
      
      <!-- 内圈水印 -->
      <div class="watermark watermark-inner-1">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-inner-2">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-inner-3">
        {{ userFullName }}
      </div>
      <div class="watermark watermark-inner-4">
        {{ userFullName }}
      </div>
    </div>
    
    <!-- 隐藏水印层 -->
    <div class="hidden-watermarks" :class="{ 'debug-visible': showHiddenWatermarks }">
      <!-- 极淡隐藏水印 -->
      <div class="hidden-watermark hidden-1" :data-user="userFullName">
        {{ watermarkText }}
      </div>
      <div class="hidden-watermark hidden-2" :data-user="userFullName">
        {{ watermarkText }}
      </div>
      <div class="hidden-watermark hidden-3" :data-user="userFullName">
        {{ watermarkText }}
      </div>
    </div>
    
    <!-- 动态水印层 -->
    <div class="dynamic-watermarks" :class="{ 'debug-visible': showHiddenWatermarks }">
      <div
          v-for="(mark, index) in dynamicMarks"
          :key="`dynamic-${index}`"
          class="dynamic-watermark"
          :style="{
            left: mark.x + 'px',
            top: mark.y + 'px',
            opacity: showHiddenWatermarks ? 0.8 : mark.opacity,
            color: showHiddenWatermarks ? 'rgba(255, 165, 0, 0.8)' : mark.color,
            transform: `rotate(${mark.rotation}deg)`,
            border: showHiddenWatermarks ? '1px solid orange' : 'none',
            backgroundColor: showHiddenWatermarks ? 'rgba(255, 165, 0, 0.1)' : 'transparent'
          }"
        >
          {{ userFullName }}
        </div>
    </div>
    
    <!-- 背景纹理水印 -->
    <div class="texture-watermark" :class="{ 'debug-visible': showHiddenWatermarks }" :style="{ backgroundImage: texturePattern }"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 获取用户全名
const userFullName = computed(() => {
  // 优先从authStore获取
  if (authStore.user && authStore.user.fullName) {
    return authStore.user.fullName
  }
  
  // 从localStorage获取
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || 'null')
    if (userInfo && userInfo.fullName) {
      return userInfo.fullName
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
  }
  
  return null
})

// 检测深色模式
const isDarkMode = computed(() => {
  // 检查系统深色模式
  if (window.matchMedia) {
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }
  return false
})

// 水印文本（包含时间戳和用户信息）
const watermarkText = computed(() => {
  if (!userFullName.value) return ''
  const timestamp = new Date().toISOString().slice(0, 19).replace('T', ' ')
  return `${userFullName.value} ${timestamp}`
})

// 动态水印位置
const dynamicMarks = ref([])

// 纹理水印模式
const texturePattern = computed(() => {
  if (!userFullName.value) return ''
  // 根据深色模式选择颜色
  const fillColor = isDarkMode.value ? 'rgba(255,255,255,0.01)' : 'rgba(0,0,0,0.01)'
  // 创建SVG纹理模式
  const svgPattern = `
    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
      <defs>
        <pattern id="watermark" x="0" y="0" width="200" height="200" patternUnits="userSpaceOnUse">
          <text x="100" y="100" text-anchor="middle" 
                font-family="Arial" font-size="12" 
                fill="${fillColor}" 
                transform="rotate(-45 100 100)">
            ${userFullName.value}
          </text>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#watermark)"/>
    </svg>
  `
  // 使用encodeURIComponent处理中文字符
  return `url("data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgPattern)}")`
})

// 生成随机动态水印位置
const generateDynamicMarks = () => {
  const marks = []
  const count = 7 // 动态水印数量（加上13个固定水印，总共20个）
  
  for (let i = 0; i < count; i++) {
    marks.push({
      x: Math.random() * (window.innerWidth - 100),
      y: Math.random() * (window.innerHeight - 50),
      opacity: Math.random() * 0.03 + 0.01, // 稍微提高透明度
      rotation: Math.random() * 360,
      color: isDarkMode.value ? 'rgba(255, 255, 255, 0.02)' : 'rgba(0, 0, 0, 0.02)'
    })
  }
  
  dynamicMarks.value = marks
}

// 定时更新动态水印位置
let dynamicInterval = null

// 防截图检测
const handleScreenshotDetection = () => {
  console.warn('检测到可能的截图行为')
  // 增加水印密度
  generateDynamicMarks()
}

// 开发者调试功能 - 显示隐藏水印
const showHiddenWatermarks = ref(false)

// 监听开发者快捷键 Ctrl+Shift+W 来切换隐藏水印显示
const toggleHiddenWatermarks = () => {
  document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.shiftKey && e.key === 'W') {
      showHiddenWatermarks.value = !showHiddenWatermarks.value
      console.log(`隐藏水印显示: ${showHiddenWatermarks.value ? '开启' : '关闭'}`)
      console.log('提示: 按 Ctrl+Shift+W 可切换隐藏水印显示状态')
    }
  })
}

const detectScreenshot = () => {
  // 检测页面失焦（可能在截图）
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      handleScreenshotDetection()
    }
  })
  
  // 检测右键菜单（可能要保存图片）
  document.addEventListener('contextmenu', (e) => {
    e.preventDefault()
    handleScreenshotDetection()
  })
  
  // 检测键盘截图快捷键
  document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey && e.shiftKey && e.key === 'S') || // Chrome截图
        (e.key === 'PrintScreen') || // 系统截图
        (e.metaKey && e.shiftKey && e.key === '4')) { // Mac截图
      e.preventDefault()
      handleScreenshotDetection()
    }
  })
}

onMounted(() => {
  generateDynamicMarks()
  detectScreenshot()
  toggleHiddenWatermarks()
  
  // 监听深色模式变化
  if (window.matchMedia) {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      // 深色模式变化时重新生成动态水印以更新颜色
      generateDynamicMarks()
    })
  }
  
  // 每30秒更新一次动态水印位置
  dynamicInterval = setInterval(() => {
    generateDynamicMarks()
  }, 30000)
  
  // 开发提示
  console.log('💡 开发者提示: 按 Ctrl+Shift+W 可切换隐藏水印显示状态')
})

onUnmounted(() => {
  if (dynamicInterval) {
    clearInterval(dynamicInterval)
  }
})
</script>

<style scoped>
.watermark-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 9999;
}

/* 可见水印层 */
.visible-watermarks {
  position: relative;
  width: 100%;
  height: 100%;
}

.watermark {
  position: absolute;
  font-size: 32px;
  color: rgba(0, 0, 0, 0.15);
  pointer-events: none;
  user-select: none;
  font-weight: bold;
  white-space: nowrap;
  font-family: Arial, sans-serif;
  transform: rotate(-45deg);
}

/* 中心水印 */
.watermark-center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-45deg);
  font-size: 48px;
}

/* 左上角水印 */
.watermark-top-left {
  top: 20%;
  left: 20%;
  transform: translate(-50%, -50%) rotate(-45deg);
}

/* 右上角水印 */
.watermark-top-right {
  top: 20%;
  right: 20%;
  transform: translate(50%, -50%) rotate(-45deg);
}

/* 左下角水印 */
.watermark-bottom-left {
  bottom: 20%;
  left: 20%;
  transform: translate(-50%, 50%) rotate(-45deg);
}

/* 右下角水印 */
.watermark-bottom-right {
  bottom: 20%;
  right: 20%;
  transform: translate(50%, 50%) rotate(-45deg);
}

/* 边缘中点水印 */
.watermark-top-center {
  top: 15%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-45deg);
}

.watermark-bottom-center {
  bottom: 15%;
  left: 50%;
  transform: translate(-50%, 50%) rotate(-45deg);
}

.watermark-left-center {
  top: 50%;
  left: 15%;
  transform: translate(-50%, -50%) rotate(-45deg);
}

.watermark-right-center {
  top: 50%;
  right: 15%;
  transform: translate(50%, -50%) rotate(-45deg);
}

/* 内圈水印 */
.watermark-inner-1 {
  top: 35%;
  left: 35%;
  transform: translate(-50%, -50%) rotate(-45deg);
  font-size: 28px;
}

.watermark-inner-2 {
  top: 35%;
  right: 35%;
  transform: translate(50%, -50%) rotate(-45deg);
  font-size: 28px;
}

.watermark-inner-3 {
  bottom: 35%;
  left: 35%;
  transform: translate(-50%, 50%) rotate(-45deg);
  font-size: 28px;
}

.watermark-inner-4 {
  bottom: 35%;
  right: 35%;
  transform: translate(50%, 50%) rotate(-45deg);
  font-size: 28px;
}

/* 隐藏水印层 */
.hidden-watermarks {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.hidden-watermark {
  position: absolute;
  font-size: 14px;
  font-family: Arial, sans-serif;
  font-weight: normal;
  white-space: nowrap;
  pointer-events: none;
  user-select: none;
  color: rgba(0, 0, 0, 0.002);
  transform: rotate(-30deg);
}

.hidden-1 {
  top: 15%;
  left: 30%;
  color: rgba(0, 0, 0, 0.001);
}

.hidden-2 {
  top: 60%;
  right: 25%;
  color: rgba(0, 0, 0, 0.002);
  transform: rotate(30deg);
}

.hidden-3 {
  bottom: 25%;
  left: 15%;
  color: rgba(0, 0, 0, 0.001);
  transform: rotate(-60deg);
}

/* 动态水印层 */
.dynamic-watermarks {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.dynamic-watermark {
  position: absolute;
  font-size: 10px;
  font-family: Arial, sans-serif;
  font-weight: normal;
  white-space: nowrap;
  pointer-events: none;
  user-select: none;
  transition: all 0.3s ease;
  color: rgba(0, 0, 0, 0.02);
}

#app.dark-mode .dynamic-watermark {
  color: rgba(255, 255, 255, 0.02);
}

/* 纹理水印层 */
.texture-watermark {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  opacity: 0.3;
  background-repeat: repeat;
  background-size: 200px 200px;
}

/* 深色模式下的水印 */
#app.dark-mode .watermark {
  color: rgba(255, 255, 255, 0.2);
}

#app.dark-mode .hidden-watermark {
  color: rgba(255, 255, 255, 0.002);
}

#app.dark-mode .hidden-1 {
  color: rgba(255, 255, 255, 0.001);
}

#app.dark-mode .hidden-2 {
  color: rgba(255, 255, 255, 0.002);
}

#app.dark-mode .hidden-3 {
  color: rgba(255, 255, 255, 0.001);
}

/* 系统级深色模式支持 */
@media (prefers-color-scheme: dark) {
  .watermark {
    color: rgba(255, 255, 255, 0.2);
  }

  .hidden-watermark {
    color: rgba(255, 255, 255, 0.002);
  }

  .hidden-1 {
    color: rgba(255, 255, 255, 0.001);
  }

  .hidden-2 {
    color: rgba(255, 255, 255, 0.002);
  }

  .hidden-3 {
    color: rgba(255, 255, 255, 0.001);
  }

  .dynamic-watermark {
    color: rgba(255, 255, 255, 0.02);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .watermark {
    font-size: 24px;
  }
  
  .watermark-center {
    font-size: 36px;
  }
  
  .hidden-watermark {
    font-size: 12px;
  }
  
  .dynamic-watermark {
    font-size: 8px;
  }
}

@media (max-width: 480px) {
  .watermark {
    font-size: 18px;
  }
  
  .watermark-center {
    font-size: 28px;
  }
  
  .hidden-watermark {
    font-size: 10px;
  }
  
  .dynamic-watermark {
    font-size: 6px;
  }
}

/* 防止水印被选中或复制 */
.watermark-container * {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
}

/* 防止右键菜单 */
.watermark-container {
  -webkit-context-menu: none;
  -moz-context-menu: none;
  context-menu: none;
}

/* 开发者调试模式 - 显示隐藏水印 */
.hidden-watermarks.debug-visible .hidden-watermark {
  color: rgba(255, 0, 0, 0.8) !important;
  background-color: rgba(255, 255, 0, 0.2);
  border: 1px dashed red;
  padding: 2px 4px;
}

.hidden-watermarks.debug-visible .hidden-1 {
  color: rgba(255, 0, 0, 0.8) !important;
}

.hidden-watermarks.debug-visible .hidden-2 {
  color: rgba(0, 255, 0, 0.8) !important;
}

.hidden-watermarks.debug-visible .hidden-3 {
   color: rgba(0, 0, 255, 0.8) !important;
 }
 
 /* 动态水印调试模式 */
 .dynamic-watermarks.debug-visible .dynamic-watermark {
   border: 1px solid orange !important;
   background-color: rgba(255, 165, 0, 0.1) !important;
 }
 
 /* 纹理水印调试模式 */
 .texture-watermark.debug-visible {
   opacity: 0.8 !important;
   border: 2px dashed purple;
   background-color: rgba(128, 0, 128, 0.1);
 }
 </style>